# from beaker.session import SessionMiddleware
import web
from web import form



log_in = form.Form(
            form.Textbox("login", form.notnull, description="User name"),
            form.Password("password", form.notnull, description="Password")
        )
        
def logged(session):
    if "authentic" in session:
        if session.authentic == 1:
            return True
    return False

urls = (
    '/', 'index',
    '/logout', 'logout',)

# session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'loggedin':0, 'username':"fred"})

web.config.debug = False # change this and sessions will stop working 
app = web.application(urls, globals()) #what's the diff between globals and locals here?

#added for sessions
# can use DBStore instead, but requires setup of table
# session = web.session.Session(app, web.session.DiskStore('sessions'))
session = web.session.Session(app, web.session.DiskStore('sessions3'), initializer={'authentic':0, 'username':"fred"})


users = {"ml": "123", "jl":"456","abc":"abc" }

class index:
    def GET(self):
        # session = web.ctx.session
        # session.start()
        web.header("Content-Type","text/html; charset=utf-8")
        # session = web.ctx.environ['beaker.session']
        print 7, session
        if logged(session):
            ret = "U logged as <b>%s</b>"%session.username
            return ret + "<br /><a href='/logout'>logout</a>"
        else:
            return "login failed<br /> <form name='main' method='post'> "+ log_in.render() + "<input type='submit' />"
        
    def POST(self):
        # session = web.ctx.environ['beaker.session']
        # session = web.ctx.session
        
        # print 11, web.input()
        i = web.input()
        if i.login in users and users[i.login] == i.password:
            session.authentic = 1
            session.username = i.login
        web.seeother("/")
            
class logout:
    def GET(self):
        # session = web.ctx.environ['beaker.session']
        # session.invalidate()
        # print dir(session)
        print 20, session
        session.authentic = 0
        session.kill()
        print 30, session
        web.seeother("/")
        """
        or
        session.delete()
        session.save()
        """
def session_mw(app):
    return SessionMiddleware(app, key = "sid")

if __name__ == "__main__":
    # web.run(urls, globals(), *(web.reloader, session_mw))
    app.run()
